package com.qf.flash.ui.business;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.event.FuckEvent;
import com.qf.flash.http.response.PlayConditinoResponse;
import com.qf.flash.http.response.PlayTypeBean;
import com.qf.flash.model.Pay2SponsorBean;
import com.qf.flash.model.PayParam;
import com.qf.flash.model.ScriptRoomBean;
import com.qf.flash.mvp.contract.ScriptContract;
import com.qf.flash.mvp.contract.StartTeamContract;
import com.qf.flash.mvp.presenter.ScriptPrensenter;
import com.qf.flash.mvp.presenter.StartTeamPresenter;
import com.qf.flash.ui.business.adapter.PlayTypeItem;
import com.qf.flash.ui.home.OrderPaySuccessActivity;
import com.qf.flash.ui.home.Pay2SponsorDialogFragment;
import com.qf.flash.ui.home.ScriptDetailActivity;
import com.qf.flash.ui.home.ScriptSearchActivity;
import com.qf.flash.ui.home.adapter.NumberItem;
import com.qf.flash.ui.home.adapter.ScriptRoomItem;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.DateUtil;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qf.flashlib.util.DateUtil.PATTERN_STANDARD16H;

/**
 * 描述: 商家发起活动
 * 2020/3/16 16:40
 */
public class SponsorGameActivity extends BaseActivity implements ScriptContract.View, StartTeamContract.View {
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_top_right)
    TextView tvTopRight;
    @BindView(R.id.et_group_name)
    EditText etGroupName;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.rv_type)
    RecyclerView rvType;
    @BindView(R.id.rv_money)
    RecyclerView rvMoney;
    @BindView(R.id.rv_hot)
    RecyclerView rvHot;
    @BindView(R.id.tv_sponsor)
    TextView tvSponsor;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.rv_count)
    RecyclerView rvCount;

    private TimePickerView mTimePicker;
    private Date mSelectDate;

    private RVAdapter<PlayTypeBean> mTypeAdapter;
    private RVAdapter<String> moneyAdapter;
    private RVAdapter<String> mNumberAdapter;
    private RVAdapter<ScriptRoomBean> mHotAdapter;
    private ScriptPrensenter mScriptPresenter;
    private StartTeamPresenter startTeamPresenter;
    private int pageNo = 1;
    private boolean isRefresh;
    private PlayConditinoResponse conditions;
    private boolean isByType;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, SponsorGameActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sponsor_game;
    }

    @Override
    protected void initViewAndData() {
        tvTopTitle.setText("发起活动");
        com.qf.flashlib.util.ViewUtil.setRightIcon(this, tvTopRight, R.mipmap.icon_search);
        initRvHot();
        initRvMoney();
        initRvNumber();
        initRvType();

        //初始化时间
        initTimeDialog();
        initRefresh();
        mScriptPresenter.getConditions("0", "1");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.icon_search);
        if (drawable != null) {
            drawable.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.icon_search);
        if (drawable != null) {
            drawable.setColorFilter(null);
        }
    }

    private void initRefresh() {
        mRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                pageNo++;
                getPlayListTypeData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                pageNo = 1;
                getPlayListTypeData();
            }
        });
    }

    @Override
    protected void initInject() {
        mScriptPresenter = new ScriptPrensenter();
        startTeamPresenter = new StartTeamPresenter();
        initPresenters(mScriptPresenter, startTeamPresenter);
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    private void initRvHot() {
        rvHot.setLayoutManager(new LinearLayoutManager(this));
        mHotAdapter = new RVAdapter<>(new ScriptRoomItem(this));
        rvHot.setAdapter(mHotAdapter);
        mHotAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                GroupDetailActivity.start(SponsorGameActivity.this);
                int numberPos = moneyAdapter.getSingleChosenPosition();
                int numChosenPosition = mNumberAdapter.getSingleChosenPosition();
                Pay2SponsorBean sponsorBean;
                if (numberPos != -1 && conditions != null && TextUtils.equals(moneyAdapter.getData(numberPos), "0")) {
                    sponsorBean = getSponsorBean(true);
                } else {
                    sponsorBean = getSponsorBean(false);
                }
                if (numChosenPosition != -1 && numChosenPosition != 0) {
                    sponsorBean.setNum(mNumberAdapter.getData(numChosenPosition));
                }

                ScriptRoomBean data = mHotAdapter.getData(position);
                sponsorBean.setPlayId(data.getId());
                sponsorBean.setPlayType(data.getTypeId());
                sponsorBean.setPlayName(data.getName());
                sponsorBean.setPlayTypeName(data.getTypeName());
                ScriptDetailActivity.start(SponsorGameActivity.this, sponsorBean, position);
            }
        });
        mHotAdapter.setOnItemChildClickListener((view, position) -> {
            mHotAdapter.setSingleChosenPosition(position);
            mHotAdapter.notifyDataSetChanged();
        });
        rvHot.setNestedScrollingEnabled(false);
    }


    private void initRvType() {
        final LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvType.setLayoutManager(manager);
        mTypeAdapter = new RVAdapter<>(new PlayTypeItem());
        rvType.setAdapter(mTypeAdapter);
        mTypeAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                mTypeAdapter.setSingleChosenPosition(position);
                mTypeAdapter.notifyDataSetChanged();
                PlayTypeBean data = mTypeAdapter.getData(position);
                isByType = true;
                mScriptPresenter.getConditions(data.getTemplateId(), "1");
                mRefresh.autoRefresh();
            }
        });
    }

    private void initRvMoney() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvMoney.setLayoutManager(manager);
        NumberItem numberItem = new NumberItem();
        numberItem.setUnit("元");
        moneyAdapter = new RVAdapter<>(numberItem);
        moneyAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                moneyAdapter.setSingleChosenPosition(position);
                moneyAdapter.notifyDataSetChanged();
            }
        });
        rvMoney.setAdapter(moneyAdapter);
    }

    private void initRvNumber() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvCount.setLayoutManager(manager);
        mNumberAdapter = new RVAdapter<>(new NumberItem());
        mNumberAdapter.setOnItemClickListener((view, position) -> {
            int singleChosenPosition = mNumberAdapter.getSingleChosenPosition();
            mNumberAdapter.setSingleChosenPosition(singleChosenPosition == position ? -1 : position);
            mNumberAdapter.notifyDataSetChanged();
            getPlayListTypeData();
        });
        rvCount.setAdapter(mNumberAdapter);
    }

    //    private void setTypeTestData() {
//        List<String> data = new ArrayList<>();
//        data.add("剧本杀");
//        data.add("狼人杀");
//        data.add("密室逃脱");
//        mTypeAdapter.setSingleChosenPosition(0);
//        mTypeAdapter.setDatas(data);
//    }
//    private void setNumberTestData() {
//        List<String> data = new ArrayList<>();
//        data.add("免费");
//        data.add("30元");
//        data.add("40元");
//        data.add("50元");
//        data.add("60元");
//        data.add("70元");
//        data.add("80元");
//        data.add("90元");
//        mNumberAdapter.setSingleChosenPosition(0);
//        mNumberAdapter.setDatas(data);
//    }


    @OnClick({R.id.tv_top_back, R.id.tv_date, R.id.tv_sponsor, R.id.ll_top_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:
                finish();
                break;
            case R.id.tv_date:
                if (mTimePicker != null)
                    hideInput();
                mTimePicker.show();
                break;
            case R.id.tv_sponsor:
                sponsorGame();
                break;
            case R.id.ll_top_right:
                int numberPos = moneyAdapter.getSingleChosenPosition();
                Pay2SponsorBean sponsorBean;
                if (numberPos != -1 && conditions != null && TextUtils.equals(moneyAdapter.getData(numberPos), "0")) {
                    sponsorBean = getSponsorBean(true);
                } else {
                    sponsorBean = getSponsorBean(false);
                }
                ScriptSearchActivity.start(this, sponsorBean, "请输入剧本名称");
                break;
        }
    }

    private void getPlayListTypeData() {
        int moneyPosition = moneyAdapter.getSingleChosenPosition();
        int mTypeChosenPos = mTypeAdapter.getSingleChosenPosition();
        int chosenPosition = mNumberAdapter.getSingleChosenPosition();

        HashMap<String, Object> map = new HashMap<>();
        map.put("typeId", 0);
        if (mTypeChosenPos != -1) {
            map.put("typeId", mTypeAdapter.getData(mTypeChosenPos).getId());
        }

        if (moneyPosition != -1) {
            map.put("money", moneyAdapter.getData(moneyPosition));
        }
        if (chosenPosition != -1 && chosenPosition != 0) {
            map.put("num", mNumberAdapter.getData(chosenPosition));
        }


        map.put("pageNo", pageNo);
        map.put("userId", UserMgr.getInstance().getLoginUser().getUid());
        map.put("pageSize", 30);
        mScriptPresenter.getShopPlayList(map);
    }


    /**
     * 弹出选择时间
     */
    private void initTimeDialog() {
        //标题颜色
        int color = getResources().getColor(R.color.color_333333);
        //选中的时间
        Calendar selectedDate = Calendar.getInstance();
        if (mSelectDate != null)
            selectedDate.setTime(mSelectDate);
        //开始时间
        Calendar startDate = Calendar.getInstance();
        //结束时间
        Calendar endDate = Calendar.getInstance();
        endDate.set(2100, 11, 31);
        //构建选择器
        mTimePicker = new TimePickerBuilder(this, mTimeListener)
                .setType(new boolean[]{true, true, true, true, true, false})  // 默认全部显示
                .setOutSideCancelable(true)                                     //点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)                                                //是否循环滚动
                .setSubmitColor(color)                                          //确定按钮文字颜色
                .setCancelColor(color)                                          //取消按钮文字颜色
                .setDate(selectedDate)                                          // 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)
                .setLabel("年", "月", "日", "时", "分", "秒")                     //默认设置为年月日时分秒
                .isCenterLabel(false)                                            //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)                                                //是否显示为对话框样式
                .build();
    }

    /**
     * 选择时间监听
     */
    private OnTimeSelectListener mTimeListener = new OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            //记录时间
            mSelectDate = date;
            tvDate.setText(DateUtil.getDateToString(date.getTime(), PATTERN_STANDARD16H));
        }
    };

    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    private void sponsorGame() {
        if (TextUtils.isEmpty(etGroupName.getText())) {
            FlashLib.showToast("请输入组队名称");
            return;
        }
        if (TextUtils.isEmpty(tvDate.getText())) {
            FlashLib.showToast("请选择时间");
            return;
        }
//        int chosenPosition = mHotAdapter.getSingleChosenPosition();
//        if (chosenPosition == -1) {
//            FlashLib.showToast("请选择剧本");
//            return;
//        }
        int numberPos = moneyAdapter.getSingleChosenPosition();
        if (numberPos != -1 && conditions != null && TextUtils.equals(moneyAdapter.getData(numberPos), "0")) {
            //免费发起组队
            startTeamPresenter.startTeam(getSponsorBean(true));
        } else {
            Pay2SponsorDialogFragment.newInstarnce(getSponsorBean(false))
                    .show(getSupportFragmentManager());
        }
    }

    private Pay2SponsorBean getSponsorBean(boolean isFree) {
        Pay2SponsorBean bean = new Pay2SponsorBean();
        bean.setTeamName(etGroupName.getText().toString());
        bean.setStartTime(tvDate.getText().toString());
        int position = moneyAdapter.getSingleChosenPosition();
        if (position != -1) {
            String data = moneyAdapter.getData(position);
            bean.setMoney(Double.parseDouble(data));
        }
        int numChosen = mNumberAdapter.getSingleChosenPosition();
        if (numChosen != -1 && numChosen != 0) {
            String data = mNumberAdapter.getData(numChosen);
            bean.setNum(data);
        }
        int typePos = mTypeAdapter.getSingleChosenPosition();
        if (typePos != -1) {
            PlayTypeBean data = mTypeAdapter.getData(typePos);
            bean.setPlayType(data.getId());
            bean.setPlayTypeName(data.getName());
        }
        bean.setPassword(etPassword.getText().toString());
        int chosenPosition = mHotAdapter.getSingleChosenPosition();
        if (chosenPosition != -1) {
            bean.setPlayId(mHotAdapter.getData(chosenPosition).getId());
            bean.setPlayName(mHotAdapter.getData(chosenPosition).getName());
            if (isFree)
                bean.setMoney(0);
            else
                bean.setMoney(mHotAdapter.getData(chosenPosition).getDownpayment());
        }
        bean.setIsShopEnter(1);
        return bean;
    }

    @Override
    public void setPlayListData(List<ScriptRoomBean> data, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
        mRefresh.setEnableLoadMore(pageNo < totalPage);
        for (ScriptRoomBean datum : data) {
            datum.setSpanSize(3);
        }
        if (isRefresh) {
            mHotAdapter.setDatas(data);
        } else {
            mHotAdapter.addData(data);
        }
    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, isRefresh);
    }

    @Override
    public void setConditionData(PlayConditinoResponse response) {
        conditions = response;
        if (isByType) {
            List<String> nums = response.getNums();
            nums.add(0, "全部");
            mNumberAdapter.setSingleChosenPosition(0);
            mNumberAdapter.setDatas(nums);
            mRefresh.autoRefresh();
        } else {
            if (response.getTypes().size() > 0) {
                mTypeAdapter.setSingleChosenPosition(0);
                PlayTypeBean data = response.getTypes().get(0);
                isByType = true;
                mScriptPresenter.getConditions(data.getTemplateId(), "1");
            }
            mTypeAdapter.setDatas(response.getTypes());
            moneyAdapter.setDatas(response.getMoneys());
        }


    }

    @Subscribe
    public void onFuckEvent(FuckEvent event) {
        if (event.getPosition() != -1) {
            mHotAdapter.setSingleChosenPosition(event.getPosition());
            mHotAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void startSuccess(PayParam payParam) {
        OrderPaySuccessActivity.start(this, payParam.getOrderId(), true);
    }
}
